import { ApiService } from './ApiService'
import { Constants } from '../utils/Constants'

/**
 * 订单服务类
 */
export class OrderService {
  private static instance: OrderService
  private apiService: ApiService

  private constructor() {
    this.apiService = ApiService.getInstance()
  }

  /**
   * 获取单例实例
   */
  static getInstance(): OrderService {
    if (!this.instance) {
      this.instance = new OrderService()
    }
    return this.instance
  }

  /**
   * 创建订单
   */
  async createOrder(orderData: {
    restaurantId: string
    items: any[]
    deliveryAddress: string
    phoneNumber: string
    remark?: string
    paymentMethod: string
  }): Promise<any> {
    try {
      const order = {
        ...orderData,
        status: Constants.ORDER_STATUS_PENDING,
        paymentStatus: Constants.PAYMENT_STATUS_UNPAID,
        deliveryFee: Constants.DELIVERY_FEE,
        packagingFee: Constants.PACKAGING_FEE,
        createTime: new Date().toISOString()
      }
      
      return await this.apiService.createOrder(order)
    } catch (error) {
      console.error('创建订单失败:', error)
      throw error
    }
  }

  /**
   * 获取用户订单列表
   */
  async getUserOrders(userId: string, status?: string): Promise<any> {
    try {
      const params = { userId }
      if (status) {
        params['status'] = status
      }
      return await this.apiService.getOrders(params)
    } catch (error) {
      console.error('获取订单列表失败:', error)
      throw error
    }
  }

  /**
   * 获取订单详情
   */
  async getOrderDetail(orderId: string): Promise<any> {
    try {
      return await this.apiService.getOrderDetail(orderId)
    } catch (error) {
      console.error('获取订单详情失败:', error)
      throw error
    }
  }

  /**
   * 取消订单
   */
  async cancelOrder(orderId: string, reason?: string): Promise<any> {
    try {
      return await this.apiService.updateOrderStatus(orderId, Constants.ORDER_STATUS_CANCELLED)
    } catch (error) {
      console.error('取消订单失败:', error)
      throw error
    }
  }

  /**
   * 确认收货
   */
  async confirmOrder(orderId: string): Promise<any> {
    try {
      return await this.apiService.updateOrderStatus(orderId, Constants.ORDER_STATUS_COMPLETED)
    } catch (error) {
      console.error('确认收货失败:', error)
      throw error
    }
  }

  /**
   * 获取配送员订单
   */
  async getDeliveryOrders(deliveryId: string, status?: string): Promise<any> {
    try {
      const params = { deliveryId }
      if (status) {
        params['status'] = status
      }
      return await this.apiService.getDeliveryOrders(params)
    } catch (error) {
      console.error('获取配送订单失败:', error)
      throw error
    }
  }

  /**
   * 接单
   */
  async acceptOrder(orderId: string, deliveryId: string): Promise<any> {
    try {
      return await this.apiService.acceptOrder(orderId)
    } catch (error) {
      console.error('接单失败:', error)
      throw error
    }
  }

  /**
   * 完成配送
   */
  async completeDelivery(orderId: string, deliveryId: string): Promise<any> {
    try {
      return await this.apiService.completeDelivery(orderId)
    } catch (error) {
      console.error('完成配送失败:', error)
      throw error
    }
  }

  /**
   * 获取商家订单
   */
  async getMerchantOrders(merchantId: string, status?: string): Promise<any> {
    try {
      const params = { merchantId }
      if (status) {
        params['status'] = status
      }
      return await this.apiService.getMerchantOrders(params)
    } catch (error) {
      console.error('获取商家订单失败:', error)
      throw error
    }
  }

  /**
   * 商家接单
   */
  async acceptMerchantOrder(orderId: string, merchantId: string): Promise<any> {
    try {
      return await this.apiService.acceptMerchantOrder(orderId)
    } catch (error) {
      console.error('商家接单失败:', error)
      throw error
    }
  }

  /**
   * 商家拒单
   */
  async rejectMerchantOrder(orderId: string, merchantId: string, reason?: string): Promise<any> {
    try {
      return await this.apiService.rejectMerchantOrder(orderId, reason)
    } catch (error) {
      console.error('商家拒单失败:', error)
      throw error
    }
  }

  /**
   * 商家完成订单
   */
  async completeMerchantOrder(orderId: string, merchantId: string): Promise<any> {
    try {
      return await this.apiService.completeMerchantOrder(orderId)
    } catch (error) {
      console.error('商家完成订单失败:', error)
      throw error
    }
  }

  /**
   * 计算订单费用
   */
  calculateOrderTotal(items: any[]): number {
    const subtotal = items.reduce((total, item) => {
      return total + (item.price * item.quantity)
    }, 0)
    
    return subtotal + Constants.DELIVERY_FEE + Constants.PACKAGING_FEE
  }

  /**
   * 检查订单是否可以取消
   */
  canCancelOrder(order: any): boolean {
    const cancellableStatuses = [
      Constants.ORDER_STATUS_PENDING,
      Constants.ORDER_STATUS_CONFIRMED,
      Constants.ORDER_STATUS_PREPARING
    ]
    return cancellableStatuses.includes(order.status)
  }

  /**
   * 获取订单状态文本
   */
  getOrderStatusText(status: string): string {
    const statusMap = {
      [Constants.ORDER_STATUS_PENDING]: '待支付',
      [Constants.ORDER_STATUS_CONFIRMED]: '已确认',
      [Constants.ORDER_STATUS_PREPARING]: '制作中',
      [Constants.ORDER_STATUS_DELIVERING]: '配送中',
      [Constants.ORDER_STATUS_COMPLETED]: '已完成',
      [Constants.ORDER_STATUS_CANCELLED]: '已取消'
    }
    return statusMap[status] || '未知状态'
  }

  /**
   * 获取配送状态文本
   */
  getDeliveryStatusText(status: string): string {
    const statusMap = {
      [Constants.DELIVERY_STATUS_PENDING]: '待接单',
      [Constants.DELIVERY_STATUS_ACCEPTED]: '已接单',
      [Constants.DELIVERY_STATUS_PICKED]: '已取餐',
      [Constants.DELIVERY_STATUS_DELIVERED]: '已送达'
    }
    return statusMap[status] || '未知状态'
  }
}